﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sherwood.SignOn.Server.Models.Services;
using Sherwood.SignOn.Server.Models.ViewModels;

namespace Sherwood.SignOn.Server.Controllers
{
    public class AdministrationController : ControllerBase
    {

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Secure all requests so that they can only be performed by administrators
            if (!UserSessionHelper.IsCurrentUserAdministrator())
                Response.Redirect("~/SignIn/?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.ToString()), true);
            base.OnActionExecuting(filterContext);
        }

        //
        // GET: /UserAdmin/
        public ActionResult Index()
        {
            IEnumerable<IUserAccount> accounts = new List<IUserAccount>(); //empty list
            return View("Index", accounts);   
        }

        
        public ActionResult SearchResults(string query) 
        {
            IEnumerable<IUserAccount> accounts = Data.UserAccounts.GetUserAccounts(query);
            return PartialView("SearchResults", accounts);
        } 

        public ActionResult Details(Guid userAccountId)
        {
            IUserAccount user = Data.UserAccounts.GetUserAccount(userAccountId);
            if (user != null)
            {
                AttributeInfo[] attributes = null;
                RoleInfo[] roles = null;
                user.GetProfile(Constants.ADMIN_CLIENT_CODE, out roles, out attributes);
                UserAccountDetailsViewModel model = new UserAccountDetailsViewModel { Attributes = attributes, Roles = roles, UserAccount = user };
                return PartialView("Details", model);
            }
            else
                return new EmptyResult();
        }

        public ActionResult Delete(Guid userAccountId)
        {
            IUserAccount account = Data.UserAccounts.GetUserAccount(userAccountId);
            if (account != null)
            {
                string message = account.FirstName + " " + account.DisplayName + "'s account successfully deleted.";
                if (Data.UserAccounts.DeleteUserAccount(userAccountId))
                {
                    return Content(message);
                }
            }
            throw new Exception("Unable to delete user accounts.");
        }

        public ActionResult EnableUserAccount(Guid userAccountId, bool enable)
        {
            IUserAccount account = Data.UserAccounts.GetUserAccount(userAccountId);
            if (account != null)
            {
                account.SetEnabled(enable);
                return Details(userAccountId);
            }
            throw new Exception("User account does not exist.");
        }
    }
}
